
from PyQt5.QtWidgets import QListWidget, QListWidgetItem,QPlainTextEdit
from PyQt5.QtCore import QSize
from signal_mgr import get_signal_manager
from data.data_mgr import get_data_manager
from config.config_mgr import get_config_manager
from util import analysis


class CCodeView(QListWidget):
    """代码面板"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.content_height = 0
        self.code_view_list: list[QPlainTextEdit] = []
        self._init_connect()

    def _init_connect(self):
        """初始化信号"""
        get_signal_manager().SIGNAL_PATH_CHANGE.connect(self._refresh_data)
        get_signal_manager().SIGNAL_CHECK.connect(self._refresh_data)

    def clear_widget(self):
        """清楚面板"""
        layout = self.content_widget.layout()
        self.content_height = 0
        for widget in self.code_view_list:
            widget.setParent(None)
            layout.removeWidget(widget)


    def get_item_wight(self, data):
        """创建控件"""
        textEdit = QPlainTextEdit(data)
        textEdit.setMinimumHeight(100)
        textEdit.resize(300,100)
        return textEdit

    def _refresh_data(self):
        """更新数据"""
        self.clear()
        data_mgr = get_data_manager()
        config_option = get_config_manager().get_dict()
        chunk_list= analysis.select_and_sort(data_mgr.chunk_list, config_option)
        
        for i in range(len(chunk_list)):
            item = QListWidgetItem(self)
            chunk = chunk_list[i]
            data = chunk.to_string()
            height = (len(chunk.detail_lines) + 4) * 20
            item.setSizeHint(QSize(self.width(), height))
            self.addItem(item)
            self.setItemWidget(item, self.get_item_wight(data))
